import sys
from ptc import PTCServer
from time import time

def getToken(server):
  reading=True
  result=""
  while reading:
    char=server.recv(1)
    if char == "|":
      reading=False
    else:
      result=result+char

  return result

serverIp=sys.argv[1]
serverPort=int(sys.argv[2])
print '[File-Server] Starting server at %s:%s' % (serverIp, serverPort)
server=PTCServer(serverIp, serverPort)
server.accept()

try:
  fileSize=int(getToken(server))
except Exception, e:
  print '[File-Server] Timeout waiting client'
  server.close()
  sys.exit(0)
print '[File-Server] Received file size:', fileSize

fileName='received_file_%s' % time()
outputFile=sys.argv[3] + '/' + fileName
print '[File-Server] Going to save in file name: %s' % outputFile

with open(outputFile, 'w') as file:
  try:
    receivedSize = 0
    while receivedSize < fileSize:
      data = server.recv(1024)
      file.write(data)
      receivedSize += len(data)
      print '[File-Server] Received data so far: %s' % receivedSize
  except Exception, e:
    print '[File-Server] Timeout waiting data', e
    server.close()
    sys.exit(0)

print '[File-Server] File written, closing server'
server.close()
print '[File-Server] Server closed'
